<template>
  <!-- 招聘信息显示 -->
  <div class="buttons">
    <el-button-group
      v-for="job in recruit"
      :key="job.name"
      style="margin-bottom: 10px"
    >
      <el-button
        type="primary"
        size="large"
        @click="open(job)"
        color="#7f96ab"
        style="color: white"
        >{{ job.id }}--{{ job.name }}---{{ job.department }}--{{
          job.position
        }}</el-button
      >
      <el-button type="primary" size="large" @click="deleteJobs(job.id)">
        <el-icon class="el-icon--right"><Delete /></el-icon>
      </el-button>
    </el-button-group>
  </div>

  <!-- 职位发布抽屉 -->
  <el-drawer
    v-model="visibleDrawer"
    :title="title"
    :before-close="handleClose"
    direction="rtl"
    size="50%"
  >
    <el-form :model="staff" ref="formRef" label-width="100px">
      <!-- 招聘名称 -->
      <el-form-item label="招聘名称" prop="name">
        <el-input v-model="staff.name" placeholder="请输入招聘名称"></el-input>
      </el-form-item>

      <!-- 招聘详情 -->
      <el-form-item label="招聘详情" prop="detail">
        <div class="editor">
          <quill-editor
            ref="editorRef"
            v-model:content="staff.detail"
            content-type="html"
            theme="snow"
          ></quill-editor>
        </div>
      </el-form-item>

      <!-- 招聘部门 -->
      <el-form-item label="招聘部门" prop="department">
        <el-select v-model="staff.department" placeholder="请选择部门">
          <el-option v-for="pd in pds" :key="pd.id" :label="pd" :value="pd">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 招聘职位 -->
      <el-form-item label="招聘职位" prop="position">
        <el-radio-group v-model="staff.position">
          <el-radio
            v-for="position in positions"
            :key="position.id"
            :label="position"
            :value="position"
            >{{ position }}</el-radio
          >
        </el-radio-group>
      </el-form-item>

      <!-- 是否发布 -->
      <el-form-item>
        <div style="margin-left: 300px">
          <el-button @click="onPublish(formRef, title)" type="primary">
            {{ title === '招聘岗位添加' ? '确认发布' : '确认编辑' }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script setup>
import { ref, onMounted, nextTick, watchEffect, watch } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { useEmployeeStore } from '@/stores'
import { Delete } from '@element-plus/icons-vue'
import { deleteHire, editHire, addHire } from '../../../api/hire'

// 调用 员工store实例
const employeeStore = useEmployeeStore()

// 定义接收父级传递的 props
const props = defineProps({
  dataCheck: Array,
  dataAll: Array,
  visibleDrawerHire: Boolean
})

// 定义 emit 事件
const emit = defineEmits(['update:jobData'])

// 接受传过来的数据
const recruit = ref([])
//职位发布显示
const visibleDrawer = ref(false)
const dataAll = props.dataAll

visibleDrawer.value = props.visibleDrawerHire
watchEffect(() => {
  // // 在 props.dataCheck 变化时被调用
  recruit.value = 0
  recruit.value = props.dataCheck
  visibleDrawer.value = props.visibleDrawerHire
  if (dataAll.value) {
    recruit.value = dataAll.value.slice(0, 5)
  }
})
// 监听 props 的变化
watch(
  () => props.dataAll,
  (newData) => {
    recruit.value = newData
  },
  { immediate: true }
)

//更新数据
const recruitData = () => {
  recruit.value = props.dataCheck
}
onMounted(async () => {
  //获取部门，职位
  await employeeStore.fetchEmployeeAll()
  pds.value = employeeStore.departments
  positions.value = employeeStore.positions
})

//职位发布信息
const staff = ref({
  id: '',
  name: '',
  detail: '',
  department: '',
  position: ''
})

const formRef = ref() //弹窗数据
const editorRef = ref() //富文本
const pds = ref([]) //部门分类
const positions = ref([]) //职位分类
const updateInfo = ref(0)
// 关闭弹窗
const handleClose = () => {
  //关闭弹窗
  visibleDrawer.value = false
  //清空当前的form
  formRef.value.resetFields()

  if (editorRef.value) {
    editorRef.value.getQuill().setText('')
  }
}

//点击 编辑 添加 按钮
const title = ref('招聘岗位添加')
const open = (rowData) => {
  visibleDrawer.value = true
  nextTick(() => {
    // 如果是编辑，有参数
    if (rowData) {
      title.value = '招聘岗位编辑'
      // 浅拷贝
      Object.assign(staff.value, rowData) // 当前的 rowData 数据给 staff
    } else {
      title.value = '招聘岗位添加'
    }
  })
}
//点击编辑 添加 出现这个弹窗，点击确定 更新列表
const onPublish = async (formEl, title) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      if (title === '招聘岗位添加') {
        //添加
        const res = await addHire(staff.value)
        //关闭弹窗
        handleClose()

        // console.log(res, '添加')
        if (res.code === 200) {
          ElMessage.success('添加成功')
        }
        updateInfo.value = 1
        emit('update:jobData', updateInfo.value)
      } else {
        //编辑
        const res = await editHire(staff.value)
        // console.log(res, '编辑')

        if (res.code === 200) {
          ElMessage.success('编辑成功')
        }
        recruit.value = props.dataCheck
        updateInfo.value = 1
        emit('update:jobData', updateInfo.value)

        handleClose()
      }
    }
  })
}

// 实现删除 功能
const deleteJobs = async (jobId) => {
  await ElMessageBox.confirm('你确认要删除该职位招聘么', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
    .then(async () => {
      // 这里应该调用删除职位的API或方法，例如：
      await deleteHire(jobId)
      //跟新数据
      recruitData()
      ElMessage.success('删除成功')
      updateInfo.value = 1
      emit('update:jobData', updateInfo.value)
    })
    .catch(() => {
      ElMessage.info('用户取消了删除')
    })
}
</script>
<style lang="less" scoped>
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  //   width: 100%;

  .el-button-group {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .el-button--primary {
    width: 80%;
    margin: 5px 0; /* 按钮间距 */
  }
  .el-button-group .el-button--primary:last-child {
    flex: 1;
  }
}
</style>
